package com.suxin.log;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author Tang
 * @classname DBLog
 * @description [  ]
 * @date 2021/7/13 20:52
 */
public class DBLog extends Thread{

    private static DBLog dbLog = null;
    private static BlockingQueue<LogInfo> logInfoQueue = new LinkedBlockingDeque<>(1024);
    private ILogFeign logFeign;

    public void setLogFeign(ILogFeign logFeign) {
        this.logFeign = logFeign;
    }

    public static synchronized DBLog getInstance() {
        if (dbLog == null) {
            dbLog = new DBLog();
        }
        return dbLog;
    }

    public void offerQueue(LogInfo logInfo) {
        logInfoQueue.offer(logInfo);
    }

    @Override
    public void run() {
        while (true) {
            List<LogInfo> bufferList = new ArrayList<>(10);
            try {
                Thread.sleep(1000);
                logInfoQueue.drainTo(bufferList);
                if (bufferList.size() > 0) {
                    bufferList.forEach(item -> {
                        logFeign.saveLog(item);
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                bufferList.clear();
            }
        }
    }

    public static void main(String[] args) {
        DBLog.getInstance().start();
    }

}